<template>
  <div class="user-activity">
    <div class="top-images">
      <el-carousel :interval="3000" type="card" trigger="click" height="220px">
        <el-carousel-item v-for="item in carouselImages" :key="item">
          <img :src="item + carouselPrefix" class="image" alt="">
        </el-carousel-item>
      </el-carousel>
    </div>

    <div class="sort-box">
      <div class="left">
        <el-button
          type="primary"
          class="to-like"
          @click="showForm"
        >我要告白
        </el-button>
      </div>
      <div class="right">
        <span class="sort-label">排序：</span>
        <span class="sort-option" @click="sortList('createDate')">时间
          <i
            v-if="sortBy === 'createDate'"
            :class="sortOrder === 'DESC' ? 'el-icon-caret-bottom' : 'el-icon-caret-top'"
          />
        </span>
        <span class="sort-option" @click="sortList('comments')">评论数
          <i v-if="sortBy === 'comments'" :class="sortOrder === 'DESC' ? 'el-icon-caret-bottom' : 'el-icon-caret-top'" />
        </span>
        <span class="sort-option" @click="sortList('likes')">点赞数
          <i v-if="sortBy === 'likes'" :class="sortOrder === 'DESC' ? 'el-icon-caret-bottom' : 'el-icon-caret-top'" />
        </span>
      </div>
    </div>

    <div class="infinite-list-wrapper">
      <ul class="list">
        <li v-for="item in confessionList" :key="item.id" class="list-item">
          <el-card style="margin-bottom: 5px; width: 100%">
            <div class="post">
              <div class="user-block">
                <img
                  class="img-circle"
                  :src="avatarImages[item.avatar] + avatarPrefix"
                  alt=""
                >
                <span class="username text-muted">{{ item.nickName }}</span>
                <span class="description">{{ formatTime(new Date(item.createDate)) }}</span>
              </div>
              <p class="confession-content" @click="showConfessionDetail(item)">
                <span>{{ item.lover }}</span>
                <img src="../../../assets/icons/horn2.png" class="like-icon" alt="">
                {{ item.content }}</p>
              <ul class="list-inline">
                <li>
                  <span class="link-black text-sm" @click="tolikeConfession(item)">
                    <!-- <i class="el-icon-share" /> -->
                    <img src="../../../assets/icons/like.png" class="like-icon" alt="">{{ item.likeCount }}点赞
                  </span>
                </li>
                <li>
                  <span class="link-black text-sm">
                    <!-- <svg-icon icon-class="like" /> -->
                    <img src="../../../assets/icons/comment.png" class="like-icon" alt="">{{ item.commentCount }}条评论
                  </span>
                </li>
              </ul>
            </div>
          </el-card>
        </li>
      </ul>
      <p v-if="loading" style="text-align: center">加载中...</p>
      <p v-if="confessionNoMore" style="text-align: center">总计{{ confessionTotal }}条，没有更多了</p>
    </div>

    <el-dialog
      title="告白详情"
      :visible.sync="confessionDetailDialogVisible"
      width="80%"
      center
    >
      <ConfessionDetail :confession-detail-data="confessionDetailData" />
    </el-dialog>

    <el-dialog
      title="我要告白"
      :visible.sync="confessionDialogVisible"
      width="60%"
      center
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="avatar">
          <el-input v-if="false" v-model="form.avatar" />
          <div class="user-block">
            <img
              class="img-circle"
              :src="avatarImages[form.avatar] + avatarPrefix"
              alt=""
            >
          </div>
        </el-form-item>
        <el-form-item label="昵称" required prop="nickName">
          <el-input v-model="form.nickName" />
        </el-form-item>
        <el-form-item label="告白对象" required prop="lover">
          <el-input v-model="form.lover" />
        </el-form-item>
        <el-form-item label="告白内容" required prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            placeholder="请输入内容"
            maxlength="1024"
            :rows="5"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="createConfessionSubmit">告白♥</el-button>
          <el-button @click="confessionDialogVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Mock from 'mockjs'
import _ from 'lodash'
import { fetchConfessionList, likeConfession, createConfession } from '@/api/confession'
import { formatTime } from '@/utils/index.js'
import ConfessionDetail from '@/views/confession/components/confessionDetail.vue'

const avatarPrefix = '?imageView2/1/w/80/h/80'
const carouselPrefix = '?imageView2/2/h/440'

export default {
  components: {
    ConfessionDetail
  },
  data() {
    return {
      sortBy: '',
      sortOrder: 'DESC',
      likeQuery: { mId: '1' },
      confessionQuery: { orderType: 'createDate', order: 'DESC', page: 1, size: 10 },
      confessionList: [],
      confessionTotal: 0,
      confessionNoMore: false,
      carouselImages: [
        require('@/assets/carousel/1.png'),
        require('@/assets/carousel/2.png'),
        require('@/assets/carousel/3.png')
      ],
      avatarImages: [
        require('@/assets/avatar/1.png'),
        require('@/assets/avatar/2.png'),
        require('@/assets/avatar/3.png'),
        require('@/assets/avatar/4.png'),
        require('@/assets/avatar/5.png'),
        require('@/assets/avatar/6.png'),
        require('@/assets/avatar/7.png')
      ],
      avatarPrefix,
      carouselPrefix,
      loading: false,
      confessionDetailDialogVisible: false,
      confessionDetailData: {},
      confessionDialogVisible: false,
      form: {
        avatar: Math.floor(Math.random() * 100 % 7),
        nickName: Mock.mock('@first'),
        lover: '',
        content: ''
      },
      rules: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        lover: [
          { required: true, message: '请输入告白对象', trigger: 'blur' },
          { min: 1, max: 1024, message: '长度在 1 到 1024 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入告白内容', trigger: 'blur' },
          { min: 1, max: 1024, message: '长度在 1 到 1024 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  created() {
  },
  mounted() {
    this.getConfessionList()
    this.addScroll()
  },
  destroyed() {
    this.removeScroll()
  },
  // 删除滚动监听器，建议使用beforeRouteLeave，因为destroyed()钩子在路由跳转时不会触发
  beforeRouteLeave() {
    this.removeScroll()
  },
  methods: {
    sortList(sortBy) {
      if (this.sortBy === sortBy) {
        // 如果点击的是当前排序的字段，则切换排序顺序
        this.sortOrder = this.sortOrder === 'DESC' ? 'ASC' : 'DESC'
      } else {
        // 如果点击的是新的排序字段，则将排序字段更新为新字段，并默认按降序排序
        this.sortBy = sortBy
        this.sortOrder = 'DESC'
      }
      this.confessionQuery.orderType = this.sortBy
      this.confessionQuery.order = this.sortOrder
      this.getConfessionList(this.confessionQuery)
    },
    formatTime,
    tolikeConfession(item) {
      console.log(item)
      likeConfession(item.uId).then(function(response) {
        // 更新成功后将 item.likeCount 加一
        item.likeCount++

        // 在此处可以执行其他操作或显示反馈信息

        console.log('点赞成功')
      }).catch(function(error) {
        // 更新失败的处理
        console.error('点赞失败', error)
      })
    },
    query(orderType, order) {
      this.resetConffessionList()
      this.confessionQuery.orderType = orderType
      this.confessionQuery.order = order
      this.getConfessionList(this.confessionQuery)
    },
    resetConffessionList() {
      this.confessionList = []
      this.confessionTotal = 0
      this.confessionNoMore = false
      this.confessionQuery = { orderType: 'createDate', order: 'DESC', page: 1, size: 10 }
    },
    getConfessionList() {
      return new Promise((resolve, reject) => {
        const that = this
        fetchConfessionList(that.confessionQuery)
          .then(function(response) {
            console.log('fetchConfessionList', response)
            that.confessionList.push(...response.data.items)
            that.confessionTotal = response.data.total
            if (response.data.isLastPage) {
              that.confessionNoMore = true
            } else {
              that.confessionQuery.page++
            }
            setTimeout(function() {
              that.loading = false
            })
            resolve() // 数据获取成功，调用 resolve()
          })
          .catch(function(error) {
            console.error('fetchConfessionList error', error)
            reject(error) // 数据获取失败，调用 reject()
          })
      })
    },
    showConfessionDetail(item) {
      console.log('showConfessionDetail', item)
      this.confessionDetailData = item
      // this.confessionDetailDialogVisible = true
      this.$router.push({
        name: 'ConfessionDetails',
        params: {
          confessionDetailData: item
        }
      })
    },
    resetForm() {
      this.form = {
        avatar: Math.floor(Math.random() * 100 % 7),
        nickName: Mock.mock('@first'),
        lover: '',
        content: ''
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    showForm() {
      this.resetForm()
      this.confessionDialogVisible = true
    },
    createConfessionSubmit() {
      console.log('submit!')
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.form)
          createConfession(this.form).then(function(response) {
            that.resetConffessionList()
            that.getConfessionList()
            that.centerDialogVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 无限滚动加载 start
    // 获取当前可视范围的高度
    // getClientHeight() {
    //   let clientHeight = 0
    //   if (document.body.clientHeight && document.documentElement.clientHeight) {
    //     clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
    //   } else {
    //     clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
    //   }
    //   return clientHeight
    // },
    // // 获取文档完整的高度
    getScrollHeight() {
      return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
    },
    // 获取当前滚动条的位置
    // getScrollTop() {
    //   var scrollTop = 0
    //   // window.pageYOffset = document.documentElement.scrollTop
    //   if (document.documentElement && document.documentElement.scrollTop) {
    //     scrollTop = document.documentElement.scrollTop
    //   } else if (document.body) {
    //     scrollTop = document.body.scrollTop
    //   }
    //   return scrollTop
    // },
    getScrollTop() {
      return (window.scrollY || document.documentElement.scrollTop)
    },
    getClientHeight() {
      // 获取可视高度
      return window.innerHeight
    },
    // 回调函数
    // windowScroll() {
    //   // 获取三个值
    //   const scrollTop = this.getScrollTop()
    //   const clientHeight = this.getClientHeight()
    //   const scrollHeight = this.getScrollHeight()
    //   // 如果满足公式则，确实到底了
    //   if (scrollTop + clientHeight + 1 >= scrollHeight) {
    //     // 发送异步请求请求数据，同时携带offset并自增offset
    //     // noMore是自定义变量，如果是最后一批数据则以后都不加载
    //     console.log('到底了', scrollTop, clientHeight, scrollHeight)
    //     if (!this.loading && !this.confessionNoMore) {
    //       this.loading = true
    //       this.getConfessionList()
    //     }
    //   }
    // },
    windowScroll() {
      const scrollTop = this.getScrollTop()
      const clientHeight = this.getClientHeight()
      const scrollHeight = this.getScrollHeight()
      // 请求数据之前设置loading为true 请求完成后再将其设置为false 判断confessionNoMore的值
      if (scrollTop + clientHeight + 1 >= scrollHeight) {
        if (!this.loading && !this.confessionNoMore) {
          this.loading = true
          this.getConfessionList().then(() => {
            this.loading = false
          })
        }
      }
    },
    // 销毁滚动事件
    removeScroll() {
      console.log('removeScroll listener')
      window.removeEventListener('scroll', this.windowScroll)
    },
    addScroll() {
      console.log('addScroll listener')
      // _.throttle函数实现节流 将windowScroll方法限制为每300毫秒最多触发一次
      const throttledWindowScroll = _.throttle(this.windowScroll, 300)
      window.addEventListener('scroll', throttledWindowScroll, true)
      // window.addEventListener('scroll', this.windowScroll, true) // 监听页面滚动
    }
  }
}
</script>

<style lang="scss" scoped>
.user-activity {
  .like-icon {
    width: 16px;
    margin-bottom: -2px;
  }

  .sort-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .left {
    margin-right: 10px;
    margin-bottom: 7px;
  }

  .sort-label {
    margin-right: 5px;
  }

  .sort-option {
    margin-right: 5px;
    cursor: pointer;
    color: #409eff;
  }

  .confession-content {
    display: -webkit-box;
    line-height: 1.5;
    letter-spacing: 1px;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 16px;
    -webkit-line-clamp: 2; /* 显示的最大行数 */
  }

  .selected-sort {
    margin-left: 10px;
    font-weight: bold;
  }

  .user-block {
    .username,
    .description {
      display: block;
      margin-left: 50px;
      padding: 2px 0;
    }

    .username {
      font-size: 14px;
      color: #000;
    }

    :after {
      clear: both;
    }

    .img-circle {
      border-radius: 50%;
      width: 35px;
      height: 35px;
      float: left;
    }

    span {
      font-weight: 500;
      font-size: 12px;
    }
  }

  .infinite-list-wrapper {

    .list-item {
      display: flex;
      align-items: center;
      justify-content: center;
      //min-width: 400px;
    }

    .list {
      padding: 0;
      margin: 0;
      list-style: none none;
      overflow-y: auto;
    }
  }

  .post {
    font-size: 14px;
    color: #666;

    .image {
      width: 100%;
      height: 100%;
    }

    .user-images {
      padding-top: 20px;
    }
  }

  .list-inline {
    padding-left: 0;
    margin-left: -5px;
    list-style: none;

    li {
      display: inline-block;
      padding-right: 5px;
      padding-left: 5px;
      font-size: 13px;
    }

    .link-black {
      &:hover,
      &:focus {
        color: #999;
      }
    }
  }
}

.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}
</style>
